﻿using System;
using IQToolkit.Data.Mapping;
using System.Linq;

namespace Infrastucture.Helpers
{
    public static class PropertyHelpers
    {
        public static Guid GetPrimaryKeyValue(object obj)
        {
            Type t = obj.GetType();
            var properties = t.GetProperties();

            foreach (var p in properties)
            {
                var colAtt = (ColumnAttribute)p.GetCustomAttributes(typeof(ColumnAttribute), false).FirstOrDefault();
                
                if (colAtt != null && colAtt.IsPrimaryKey)
                {
                    return (Guid)p.GetValue(obj);
                }
            }



            return Guid.Empty;
        }

        public static Guid SetPrimaryKeyValue(object obj, Guid value)
        {
            Type t = obj.GetType();
            var properties = t.GetProperties();

            foreach (var p in properties)
            {
                var colAtt = (ColumnAttribute)p.GetCustomAttributes(typeof(ColumnAttribute), false).FirstOrDefault();

                if (colAtt != null && colAtt.IsPrimaryKey)
                {
                    p.SetValue(obj, value);
                    return GetPrimaryKeyValue(obj);
                }
            }


            return Guid.Empty;
        }
    }
}
